/*
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-08-10 11:54:04
 * @LastEditTime: 2019-08-12 17:12:12
 * @LastEditors: Please set LastEditors
 */

// 组件的本质是函数，三个参数；--req,res,next 分别为请求、响应对象和回调函数next
function logger(req,res,next){
    console.log('%s %s',req.method,req.url)
    next()   //调用next执行下一步
}

function hello(req,res,next){   //如果没有下一步  next这个参数可以不要
    res.writeHead(200,{'Content-type':'text/plain'})
    res.write('hello world')
    console.log('hello world')
    next()
}


// 只对/admin有效
function hasAdmin(req,res,next){
    console.log('has admin')
    next()
}


// 路由
function admin(req,res,next){
    console.log(req.url)
    switch (req.url) {
        case '/admin':
            res.end('\n try /users')
            break;
        case '/admin/users':
            res.end('\n ok')
            break;
        default:
            res.end('\n default')
            break;
    }
    next()
}

// basic认证的中间组件
function restrict(req,res,next){
    var authorization = req.headers.authorization
    if(!authorization) return next('没有进行验证')

    var parts = authorization.split('')
    var scheme = parts[0]
    var auth = new Buffer(parts[1],'base64').toString().split(':')
    var user = auth[0]
    var pass = auth[1]

    authenticateWithDatabase(user,pass,function(err){
        if(err) return next(err)

        next()
    })
}








const connect = require('connect')
const app = connect()
app.use(logger)   //use()调用之间组件
app.use(hello)
// app.use(restrict)
app.use('/admin',hasAdmin)  //最对/admin/的时候有用    /1/admin都没用
app.use(admin)
app.listen(3000)
// 上面可以写成 如下
// const app = require('connect')().use(logger).use(hello).listen(3000)  









function end(req,res,next){
    console.log(new Buffer(res.headers,'base64'))
    res.end('ok')
    next()
}





function user(req,res,next){
    console.log(1)
    next() 
}



function admin(req,res,next){
    console.log(req.url)
    console.log(2)
    next()
} 

app.use(end)
app.use('/admin',user)
app.use('/abc',admin)
app.listen(3000)


















